<template>
	<view>
		<view class="example">
			<uni-forms ref="valiForm" :modelValue="valiFormData">
				<uni-forms-item label="用车部门" name="userDepartment">
					<uni-easyinput v-model="valiFormData.userDepartment" placeholder="请输入用车部门"
						disabled=""></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="姓名" name="userName">
					<uni-easyinput v-model="valiFormData.userName" placeholder="请输入姓名" disabled />
				</uni-forms-item>
				<uni-forms-item label="工号" name="userId">
					<uni-easyinput v-model="valiFormData.userId" placeholder="请输入工号" disabled />
				</uni-forms-item>
				<uni-forms-item label="申请人电话" name="userPhone">
					<uni-easyinput v-model="valiFormData.userPhone" placeholder="请输入电话" disabled />
				</uni-forms-item>
				<uni-forms-item label="车型" name="autoType">
					<uni-easyinput v-model="valiFormData.autoType" placeholder="请输入车型" disabled=""></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="成员数" name="passengerNum">
					<uni-easyinput v-model="valiFormData.passengerNum" placeholder="请输入成员数" disabled />
				</uni-forms-item>
				<uni-forms-item label="取车时间" name="autoStartTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="valiFormData.autoStartTime"
						disabled />
				</uni-forms-item>
				<uni-forms-item label="截止时间" name="autoArriveTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="valiFormData.autoArriveTime"
						disabled />
				</uni-forms-item>
				<uni-forms-item label="用车事宜" name="autoUseReason">
					<uni-easyinput type="textarea" v-model="valiFormData.autoUseReason" placeholder="请输入用车事宜"
						disabled />
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
	<view class="divider"></view>
	<view class="buttenBorder">
		<uni-forms ref="secondApproval" :rules="rules" :modelValue="baseFormData">
			<uni-forms-item label="审批人" required name="approver">
				<uni-data-checkbox v-model="baseFormData.approver" :localdata="approvers" style="margin-top: 10rpx;" />
			</uni-forms-item>
			<uni-forms-item label="审批意见" required name="approvalOpinions">
				<uni-data-checkbox v-model="baseFormData.approvalOpinions" :localdata="approvalOpinions" />
			</uni-forms-item>
			<uni-forms-item label="车辆分配" required name="autoType">
				<uni-data-select v-model="baseFormData.autoType" :localdata="autoPlateNumRange"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="驾驶员分配" required name="driverType">
				<uni-data-select v-model="baseFormData.driverType" :localdata="driverTypeRange"
					@change="setDriverInfo(baseFormData.driverName)"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="审批备注">
				<uni-easyinput type="textarea" v-model="baseFormData.approvalRemarks" placeholder="请输入审批备注" />
			</uni-forms-item>
			<uni-forms-item label="驾驶员姓名">
				<uni-easyinput v-model="baseFormData.driverName" disabled />
			</uni-forms-item>
			<uni-forms-item label="驾驶员电话" name="userPhone">
				<uni-easyinput v-model="baseFormData.driverPhone" disabled />
			</uni-forms-item>
			<button type="primary" @click="dialogToggle('info')">提交</button>
		</uni-forms>
	</view>
	<uni-popup ref="alertDialog" type="dialog">
		<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="提醒" content="此操作将提交用车申请,是否继续？"
			@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
	</uni-popup>
</template>

<script>
	export default {
		data() {
			return {
				valiFormData: {
					userDepartment: "",
					userName: "",
					userId: "",
					userPhone: "",
					autoType: "",
					passengerNum: "",
					autoStartTime: "",
					autoArriveTime: "",
					autoUseReason: "",
					submitTime: "",
				},
				baseFormData: {
					approver: "",
					approvalOpinions: "",
					autoType: "",
					driverType: "",
					approvalRemarks: "",
					SelectDriverIdOptions: [],
					driverName: "",
					driverPhone: "",
					driverId: "",
				},
				approvers: [],
				approvalOpinions: [{
					text: "同意",
					value: "同意",
				}, {
					text: "不同意",
					value: "不同意",
				}],
				autoPlateNumRange: [],
				driverTypeRange: [],
				rules: {
					approver: {
						rules: [{
							required: true,
							errorMessage: "请选择审批人",
						}],
					},
					approvalOpinions: {
						rules: [{
							required: true,
							errorMessage: "请选择审批意见",
						}],
					},
					autoType: {
						rules: [{
							required: true,
							errorMessage: "请选择车辆分配",
						}],
					},
					driverType: {
						rules: [{
							required: true,
							errorMessage: "请选择驾驶员分配",
						}]
					},
				},
				SubmitApproval: {
					orderId: '',
					orderApprover: '',
					approvalResult: '',
					approvalDescribe: '',
					userId: '',
					submitTime: '',
					autoPlateNum: '',
					driverId: '',
					driverPhone: '',
				},
				SubmitAutoUserTodo: {
					userId: '',
					todoTime: '',
					todoType: '',
					orderId: '',
					todoStatus: '',
				},
				SubmitDriverTodo: {
					userId: '',
					todoTime: '',
					todoType: '',
					orderId: '',
					todoStatus: '',
				},
				SubmitTime: '',
				GeneralOrderApprover: "", //待办转入
				AutoOrderId: '', //待办转入
				UserId: '', //待办转入
				AutoOrderProgress: 3,
				TodoType: '用车申请综合办审批',
				SubmitCode: [],
			}
		},

		methods: {
			UpdateCurrentTime() {
				return new Promise((resolve) => {
					const currentDateTime = new Date();

					const year = currentDateTime.getFullYear();
					const month = String(currentDateTime.getMonth() + 1).padStart(2, '0');
					const day = String(currentDateTime.getDate()).padStart(2, '0');

					const hours = String(currentDateTime.getHours()).padStart(2, '0');
					const minutes = String(currentDateTime.getMinutes()).padStart(2, '0');
					const seconds = String(currentDateTime.getSeconds()).padStart(2, '0');

					this.SubmitTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

					console.log('Updated submit_time:', this.SubmitTime);

					resolve(); // 成功时调用 resolve()
				});
			},
			setDriverInfo() {
				const selectedDriverName = this.baseFormData.driverType;
				const selectedDriver = this.baseFormData.SelectDriverIdOptions.find(driver => driver.driverName ===
					selectedDriverName);

				if (selectedDriver) {
					this.baseFormData.driverName = selectedDriver.driverName;
					this.baseFormData.driverPhone = selectedDriver.driverPhone;
					this.baseFormData.driverId = selectedDriver.userId;
				} else {
					console.error('未找到选择的驾驶员信息');
				}
			},



			// 获取用车工单信息
			getAutoOrderById(orderId) {
				uni.request({
					url: "http://localhost:8088/getAutoOrderById?orderId=" + orderId,
					method: "GET",
					success: (res) => {
						if (res.statusCode === 200) {
							// 数据请求成功，将数据绑定到 valiFormData
							this.valiFormData = res.data.data; // 这里假设后端返回的数据结构中有一个 data 字段存储实际数据
						} else {
							console.error("数据请求失败");
						}
					},
					fail: (err) => {
						console.error("数据请求失败", err);
					},
				})
			},
			// 获取车牌号
			fetchAutoPlateNums() {
				uni.request({
					url: 'http://localhost:8088/fetchPlateNums', // 后端接口地址
					method: 'GET',
				}).then((response) => {
					console.log('Response from server:', response);

					// 根据实际后端返回的数据结构进行处理
					const responseData = response.data;

					if (responseData && responseData.data && Array.isArray(responseData.data)) {
						const autoPlateNumRange = responseData.data.map((item) => ({
							value: item.autoPlateNum,
							text: item.autoPlateNum,
						}));

						// 更新formData中的autoPlateNumRange
						this.autoPlateNumRange = autoPlateNumRange;
					} else {
						console.error('Invalid response format. Expected an array.');
					}
				}).catch((error) => {
					console.error('Failed to fetch autoPlateNums:', error);
				});
			},
			// 获取空闲驾驶员信息
			getFreeDrivers() {
				uni.request({
					url: "http://localhost:8088/queryFreeDrivers",
					method: "GET",
					success: (res) => {
						console.log(res.data)
						if (res.data.code === "0") {
							this.driverTypeRange = res.data.data.map(driver => ({
								value: driver.driverName,
								text: driver.driverName,
							}));
							this.baseFormData.SelectDriverIdOptions = res.data.data;
						}

					},
					fail: (err) => {
						console.error("数据请求失败", err);
					},
				})
			},
			// 审批流程方法
			AddAutoGeneralApproval() {
				return new Promise((resolve, reject) => {
					this.SubmitApproval.orderId = this.orderId;
					this.SubmitApproval.orderApprover = this.baseFormData.approver;
					this.SubmitApproval.approvalResult = this.baseFormData.approvalOpinions;
					this.SubmitApproval.approvalDescribe = this.baseFormData.approvalRemarks;
					this.SubmitApproval.userId = localStorage.getItem("userId");
					this.SubmitApproval.submitTime = this.SubmitTime;
					this.SubmitApproval.driverId = this.baseFormData.driverId;
					this.SubmitApproval.driverPhone = this.baseFormData.driverPhone;
					this.SubmitApproval.autoPlateNum = this.baseFormData.autoType;


					uni.request({
						url: "http://localhost:8088/addAutoGeneralApproval",
						method: "POST",
						data: this.SubmitApproval,
						success: (res) => {
							// 添加调试语句
							console.log("addAutoGeneralApproval response:", res);

							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve(); // 表示异步操作成功
							} else {
								console.log(res.data.msg);
								reject(res.data.msg); // 表示异步操作失败
							}
						},
						fail: (err) => {
							// 添加调试语句
							console.log("addAutoDPApproval error:", err);

							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},
			UpdateAutoOrderProgress() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: "http://localhost:8088/updateAutoOrderProgress?orderId=" + this.orderId +
							"&autoOrderProgress=" + this.AutoOrderProgress,
						method: "PUT",
						success: (res) => {
							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve(); // 表示异步操作成功
							} else {
								console.log(res.data.msg);
								reject(res.data.msg); // 表示异步操作失败
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},
			UpdateTodoStatus() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: "http://localhost:8088/updateTodoStatus?todoType=" + this.TodoType +
							"&orderId=" + this.orderId,
						method: "PUT",
						success: (res) => {
							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve(); // 表示异步操作成功
							} else {
								console.log(res.data.msg);
								reject(res.data.msg); // 表示异步操作失败
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},
			AddUserTodo() {
				this.SubmitAutoUserTodo.userId = this.valiFormData.userId;
				this.SubmitAutoUserTodo.todoTime = this.SubmitTime;
				this.SubmitAutoUserTodo.todoType = "用车通知";
				this.SubmitAutoUserTodo.orderId = this.orderId;
				this.SubmitAutoUserTodo.todoStatus = '未完成';

				return new Promise((resolve, reject) => {
					console.log("Submitting AdduserTodo request:", this.SubmitTodo);

					uni.request({
						url: "http://localhost:8088/insertTodo",
						method: "POST",
						data: this.SubmitAutoUserTodo,
						header: {
							'content-type': 'application/json',
						},
						success: (res) => {
							console.log("insertTodo response:", res);

							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve(); // 表示异步操作成功
							} else {
								console.log(res.data.msg);
								reject(res.data.msg); // 表示异步操作失败
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},
			AddDriverTodo() {
				this.SubmitDriverTodo.userId = this.baseFormData.driverId;
				this.SubmitDriverTodo.todoTime = this.SubmitTime;
				this.SubmitDriverTodo.todoType = "用车委派";
				this.SubmitDriverTodo.orderId = this.orderId;
				this.SubmitDriverTodo.todoStatus = '未完成';

				return new Promise((resolve, reject) => {
					console.log("Submitting Adddriverodo request:", this.SubmitTodo);

					uni.request({
						url: "http://localhost:8088/insertTodo",
						method: "POST",
						data: this.SubmitDriverTodo,
						header: {
							'content-type': 'application/json',
						},
						success: (res) => {
							console.log("insertTodo response:", res);

							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve(); // 表示异步操作成功
							} else {
								console.log(res.data.msg);
								reject(res.data.msg); // 表示异步操作失败
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},
			dialogToggle(type) {
				this.msgType = type
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {
				console.log('点击确认')
				this.submit('secondApproval');
			},
			dialogClose() {
				console.log('点击取消')
			},
			submit(ref) {
				this.$refs[ref].validate().then(() => {
					console.log("Form submission successful");
					console.log("Submitted data:", this.baseFormData);
					uni.showToast({
						title: `校验通过`,
						duration: 1000
					});

					// Chain of asynchronous operations
					this.UpdateCurrentTime()
						.then(() => this.AddAutoGeneralApproval())
						.then(() => this.UpdateAutoOrderProgress())
						.then(() => this.UpdateTodoStatus())
						.then(() => this.AddUserTodo())
						.then(() => this.AddDriverTodo())
						.catch((err) => {
							console.error("An error occurred during asynchronous operations:", err);
							uni.showToast({
								title: `操作失败: ${err.message || "未知错误"}`,
								icon: "none",
								duration: 1000
							});
						});
				}).catch((err) => {
					console.error("Form validation error:", err);

					// 如果是异步验证错误，可能需要查看具体的错误对象
					if (err instanceof Error) {
						console.error("Detailed error:", err);
					}

					uni.showToast({
						title: `校验失败: ${err.message || "未知错误"}`,
						icon: "none",
						duration: 1000
					});
				});
			}


		},
		created() {
			const orderId = this.$route.query.orderId || ""; // 如果没有 orderId 参数，默认设置为空字符串
			this.orderId = orderId;
			console.log(this.orderId);
			this.approvers.push({
				text: localStorage.getItem("userName"),
				value: localStorage.getItem("userName")
			});
			this.fetchAutoPlateNums();
			this.getAutoOrderById(orderId);
			this.getFreeDrivers();
		}
	}
</script>

<style lang="scss">
	.divider {
		margin: 20rpx;
		background: #000;
		width: 95%;
		height: 1rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}

	.buttenBorder {
		padding: 15px;
		background-color: #fff;
	}
</style>